<script lang="ts" setup>
import { useGlobalDialog } from '@/hooks'
import { initPageDTO, initPageVO, type PageDTO, type PageVO, type ResultType } from '@/type/type'
import { ClassifyEnum, DialogEnum } from '@/enum'
import { useSystemStore } from '@/stores/system'
import {
  addAlbumApi,
  type AlbumDTO,
  type AlbumVO,
  albumVO2DTO,
  delAlbumApi,
  getAlbumAdminPageApi,
  initAlbumDTO,
  updateAlbumApi
} from '@/request/api/album'
import { addToFormData, isEmpty } from '@/utils'
import { useTemporaryStore } from '@/stores/temporary'

const { globalDialog } = useGlobalDialog()
const systemStore = useSystemStore()
const temporaryStore = useTemporaryStore()

// 表单
const form = ref<AlbumDTO>(initAlbumDTO())
const formRef = ref<any>()
// 多选框 id
const ids = ref<number[]>([])
const isAdd = ref<boolean>(false)

/** 查询列表 */
const pageVO = ref<PageVO<AlbumVO>>(initPageVO())

const page = ref<PageDTO>(initPageDTO())

const rules = {
  title: [{ required: true, message: '名字不能为空', trigger: 'blur' }],
  roleId: [{ required: true, message: '名字不能为空', trigger: 'blur' }],
  labelId: [{ required: true, message: '类别不能为空', trigger: 'blur' }],
  introduction: [{ required: true, message: '简介不能为空', trigger: 'blur' }]
}

const getList = () => {
  getAlbumAdminPageApi(page.value).then((res: ResultType<PageVO<AlbumVO>>) => {
    pageVO.value = res.data
  })
}

// 多选框选中数据
const handleSelectionChange = (selection: AlbumVO[]) => {
  ids.value = selection.map((item) => item.id)
}

/** 新增、修改按钮操作 */
const handle = (add: boolean, row?: AlbumVO) => {
  form.value = initAlbumDTO()
  systemStore.dialog.album = true
  isAdd.value = add
  if (!add && row) {
    form.value = albumVO2DTO(row)
    temporaryStore.form.roleId = row.roleId
    temporaryStore.setUploadUrls(row.paths)
  }
}

/** 提交按钮 */
function submitForm() {
  form.value.labelId = temporaryStore.form.labelId
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    if (form.value.id != undefined) {
      await globalDialog('确定修改 ID 为"' + form.value.id + '"的相册?').then((res: boolean) => {
        if (res) {
          // 更新图片地址
          const paths = []
          for (let i = 0; i < temporaryStore.upload.urls.length; i++) {
            paths.push(temporaryStore.upload.urls[i].url)
          }
          form.value.path = paths.toString()
          const formData = addToFormData(temporaryStore.upload.formData, form.value)
          updateAlbumApi(formData).then(() => {
            systemStore.dialog.album = false
            temporaryStore.upload.init()
            getList()
          })
        }
      })
    } else {
      if (isEmpty(temporaryStore.upload.formData.get('files'))) {
        ElMessage.error('请先上传照片！')
        return
      }
      const formData = addToFormData(temporaryStore.upload.formData, form.value)
      await addAlbumApi(formData).then(() => {
        temporaryStore.upload.init()
        systemStore.dialog.album = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (idArr: Array<number>) => {
  await globalDialog('确定删除 ID 为"' + idArr + '"的相册?').then((res: boolean) => {
    if (res) {
      delAlbumApi(idArr).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

/** 启用停用按钮操作 */
const handleChangeStatus = async (id: number, status: boolean) => {
  const dto: FormData = new FormData()
  dto.append('id', id + '')
  dto.append('status', status + '')
  const title = status ? '启用' : '停用'
  await globalDialog('确定' + title + ' ID 为"' + id + '"的相册?').then((res: boolean) => {
    if (res) {
      updateAlbumApi(dto).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<template>
  <el-container class="pt-5 gap-3" direction="vertical">
    <el-container class="pb-2 px-5" direction="vertical">
      <QueryForm
        :search="getList"
        :type="ClassifyEnum.ALBUM"
        @update="
          (args: Record<string, any>) => {
            page.param = args
          }
        "
      />
      <el-container class="gap-3">
        <el-button class="!px-2 !m-0" plain type="primary" @click="handle(true)">
          <SvgIcon message="新增" name="add" />
        </el-button>
        <el-button
          :disabled="ids.length === 0"
          class="!px-2 !m-0"
          plain
          type="danger"
          @click="handleDelete(ids)"
        >
          <SvgIcon message="删除" name="delete" />
        </el-button>
      </el-container>
    </el-container>

    <el-table :data="pageVO.list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" />
      <el-table-column label="相册标题" prop="title" width="200" />
      <el-table-column label="照片" prop="title" width="150">
        <template #default="scope">
          <el-image :src="scope.row.paths[0]" class="rounded" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="类别名" prop="label.classifyName" width="120" />
      <el-table-column label="标签名" prop="label.name" width="120" />
      <el-table-column label="简介" prop="introduction" show-overflow-tooltip />
      <el-table-column label="创建时间" prop="createTime" width="120" />
      <el-table-column label="状态" prop="status" width="70">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="110">
        <template #default="scope">
          <el-button class="!p-2 !m-1" type="primary" @click="handle(false, scope.row)">
            <SvgIcon name="edit" />
          </el-button>
          <el-button
            v-if="!scope.row.status"
            class="!p-2 !m-1"
            type="success"
            @click="handleChangeStatus(scope.row.id, true)"
          >
            <SvgIcon name="refresh" />
          </el-button>
          <el-button
            v-else
            class="!p-2 !m-1"
            type="danger"
            @click="handleChangeStatus(scope.row.id, false)"
          >
            <SvgIcon name="error" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <PageBox
      :total="pageVO.total"
      @update="
        (args: PageDTO) => {
          page = args
          getList()
        }
      "
    />
    <!-- 添加或修改对话框 -->
    <DialogTemplate :attribute="DialogEnum.ALBUM" :title="isAdd ? '新增相册' : '修改相册'">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <ClassifyLabelForm :type="ClassifyEnum.ALBUM" />
        <RoleForm @update="(value: number) => (form.roleId = value)" />
        <el-form-item label="文件" prop="files">
          <UploadImg :multiple="9" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input
            v-model="form.introduction"
            :rows="10"
            maxlength="200"
            placeholder="请输入"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <el-container class="justify-between">
        <el-button type="info" @click="systemStore.dialog.album = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </el-container>
    </DialogTemplate>
  </el-container>
</template>
